/**
 * Created by Dell on 2017.10.10.
 */

var Token ='123';
var GYZCJsonLayer = null;
var showOrHide_right = false ;
var showOrHide_left = true ;
var myMap;
var locationLevel = 18;
var oldObjInfo = {};
var stationInfo = {};
var reg_select = null;
var chr_select = null;
var chrsy_select = null;
var DWType_select = null;
var UsingStatus_select = null;
var turnLevel = 14;
var zoomType;
var Polygons = [],Points = [];
var highLightLayer = null;
var highLightData = {};
var editorPolygons = [];
var polygonLayer_editor = null;//编辑图层
var ifGetFa = true;
var newPolygonData = [];
var aa = 0 ;
var editor_id=null;
var editFlag = false;
$(function(){

    //添加地图-----------------------------begin
    myMap = L.map("maps", {
        crs : L.CRS.EPSG4326,
        center: [28.9, 120.03],
        zoom: 18,
        //maxBounds : bounds,
        layers: [normal],
        zoomControl: false,
        //measureControl: true,
        //layersControl: true,

    });

    drawnItems = L.featureGroup().addTo(myMap);

    var overlayLayers={
        "乡镇界线" : BountTileLayer.tileLayer,
        //"绘制图层":drawnItems,
    };

    L.control.layers(baseLayers, overlayLayers,{
        position:"topleft"
    }).addTo(myMap);

    //测量工具
    var options_measure = {
        localization: 'cn',
        position: 'topleft',
        primaryLengthUnit: 'meters',// 长度单位
        primaryAreaUnit: 'sqmeters',   // 面积单位
        activeColor: '#ff0000',
        completedColor: '#ff0000'
    };
    var measureControl = L.control.measure(options_measure).addTo(myMap);

    $(".zoomIn").on("click",function(){
        myMap.zoomIn();
    });

    $(".zoomOut").on("click",function(){
        myMap.zoomOut();
    });

    var aaurl = config.serviceUrl+ "/api/Fa";
    if(myMap.getZoom() <= turnLevel){
        zoomType= false;
    }else{
        zoomType= true;
    }
    $.post(aaurl, {
            "DATA": {
                "Action": "getGeometry",  //SearchByID,SearchByXY,Search
                "Token":Token,
            }
        },
        function (data) {
            if(data.GeoJsonPolygons.length>0){
                for(var i=0;i<data.GeoJsonPolygons.length;i++){
                    if(data.GeoJsonPolygons[i] != null){
                        Polygons.push(data.GeoJsonPolygons[i])
                    }
                }
                for(var i=0;i<data.GeoJsonPoints.length;i++){
                    if(data.GeoJsonPoints[i] != null){
                        Points.push(data.GeoJsonPoints[i])
                    }
                }
            }
            showLayers(myMap.getZoom())
        }
    );

    myMap.on('zoomend', function(e) {
        zoomLayers(e.target.getZoom(),highLightData)
    });

    // 点击获取经纬度
    myMap.on('click', function(e) {
        //polygonLayer_editor.clearLayers();
        var LevelXY = myMap.getZoom()+','+e.latlng.lng+','+e.latlng.lat;
        test_SearchByXY(LevelXY);
    });


    function filterLayer(obj,ID){
        for(var i in obj){
            if(obj[i].feature != undefined && obj[i].feature.properties.ID == ID){
                return obj[i];
            }
        }
    }

    //------添加
    var options = {
        position: 'bottomright', // toolbar position, options are 'topleft', 'topright', 'bottomleft', 'bottomright'
        drawMarker: false,  // adds button to draw markers
        drawPolyline: false,  // adds button to draw a polyline
        drawRectangle: false,  // adds button to draw a rectangle
        drawPolygon: true,  // adds button to draw a polygon
        drawCircle: false,  // adds button to draw a cricle
        cutPolygon: false,  // adds button to cut a hole in a polygon
        editMode: true,  // adds button to toggle edit mode for all layers
        removalMode: true   // adds a button to remove layers
    };
    $('.drawStart').click(function(){
        if(highLightLayer != null){highLightLayer.clearLayers();}
        ifGetFa = false;
        myMap.pm.addControls(options);
        $(this).hide();
        $('.drawEnd').show();
        if(showOrHide_right){
            $('.leaflet-right .leaflet-control').css('margin-right','380px')
        }else{
            $('.leaflet-right .leaflet-control').css('margin-right','20px')
        }
        if(filterLayer(myMap._layers,editor_id)){
            filterLayer(myMap._layers,editor_id).remove();
        }
        polygonLayer_editor.clearLayers();
        if(oldObjInfo.GeometryJsonPolygonStr!==undefined && oldObjInfo.GeometryJsonPolygonStr != ''){    //当前有图层
            polygonLayer_editor.addData(editorPolygons);
        }
    });
    $('.drawEnd').click(function(){
        ifGetFa = true;
        myMap.pm.removeControls(options);
        //myMap.pm.disableDraw('Poly');
        myMap.pm.disableGlobalEditMode();
        $(this).hide();
        $('.drawStart').show();
    });

    polygonLayer_editor= L.geoJSON(null).addTo(myMap);
    var options_d = {
        snappable: true,
        snapDistance: 5,
        allowSelfIntersection: false,
        templineStyle: {
            color: 'red',
        },
        hintlineStyle: {
            color: 'red',
            dashArray: [5, 5],
        },
        cursorMarker: false,
        finishOnDoubleClick: false,
        finishOn: 'dblclick',
        markerStyle: {
            opacity: 0.5,
            draggable: true,
        }
    };
    myMap.pm.enableDraw('Poly', options_d);
    myMap.pm.disableDraw('Poly');
    //var layer = null;

    myMap.on('pm:drawstart', function(e) {
        layer = e.workingLayer;
        layer.on('pm:vertexadded', function(e) {
        });
    });

    myMap.on('pm:create', function(e) {
        editFlag = true;
        aa++;
        if(aa == 1){
            polygonLayer_editor.clearLayers();
            //if(oldObjInfo.GeometryJsonPolygonStr!==undefined && oldObjInfo.GeometryJsonPolygonStr != ''){    //当前有图层
            //    polygonLayer_editor.addData(editorPolygons);
            //}
            //else{
                editorPolygons = [];
                var PolygonsData = [];
                for(var i=0;i< e.layer._latlngs[0].length;i++){
                    var array = [];
                    array.push(e.layer._latlngs[0][i].lng);
                    array.push(e.layer._latlngs[0][i].lat);
                    PolygonsData.push(array)
                }
                PolygonsData.push([e.layer._latlngs[0][0].lng,e.layer._latlngs[0][0].lat]);
                newPolygonData = [PolygonsData];
                var coordinates = [PolygonsData];
                var obj = {};
                var geometry = {};
                geometry.coordinates = coordinates;
                geometry.type = "Polygon";
                obj.geometry = geometry;
                obj.properties = {};
                obj.type = "Feature";
                editorPolygons.push(obj);
                polygonLayer_editor.addData(editorPolygons);
                e.layer.remove();
            //}
        }
        else{
            $.toast({
                text: '最多画一个图形',
                icon: 'info',
                position: "mid-center",
                stack: false,
                allowToastClose: false,
                loader: false,
                bgColor: "#3bb9d4",
                textColor: "#fff",
                timeout: 2000,
            });
        }

    });

    //---------修改
    polygonLayer_editor.on('pm:edit', function(e) {
        editFlag = true;
        if(highLightLayer != null){
            highLightLayer.clearLayers();
        }
        var latlngs = getObjFirst(e.target._layers)._latlngs[0];
        var _newPolygonData = [];
        for(var i=0;i<latlngs.length;i++){
            var data = [latlngs[i].lng,latlngs[i].lat];
            _newPolygonData.push(data)
        }
        _newPolygonData.push([latlngs[0].lng,latlngs[0].lat]);
        newPolygonData = [_newPolygonData];
    });

    //------------删除
    myMap.on('pm:remove', function(e) {
        //newPolygonData = [];
        //console.log(e.layer._latlngs)
    });


    //添加地图-----------------------------end


    $('.hideBtn_right').css('top',($('.right_panel').height()-$('.hideBtn_right').height()-50)/2+'px');
    $('.hideBtn_left').css('top',($('.left_panel').height()-$('.hideBtn_left').height()-50)/2+'px');
    $(".treelist").height($('.left_panel').height()-$('.treeTabs').height() - 20);
    $('.ctab_cont').css('max-height',($('.right_panel').height()-$('.sortBox').height() - 50)+'px');
    var d_cont =$('.right_panel').height() - $('.tt').height() - $('.imagesBox').height()- $('.d_tabs').height() -80;
    $('.d_cont').height(d_cont);

    $('.legBtn').click(function(){
        $(this).hide();
        $('.legInfo').show();
    });

    $('.closeLen').click(function(){
        $('.legInfo').hide();
        $('.legBtn').show();
    });

    // 点击箭头 绘制窗口显示隐藏
    $('.hideBtn_right').click(function(){
        console.log(showOrHide_right)
        if(showOrHide_right){
            $('.right_panel').animate({right:'-340px'},500);
            $('.drawCon').animate({right:'20px'},500);
            $('.hideIcon_right').addClass('hide');
            showOrHide_right = false;
            $('.leaflet-right .leaflet-control').animate({'margin-right':'20px'},500)
        }else {
            $('.right_panel').animate({right:'20px'},500);
            $('.drawCon').animate({right:'380px'},500);
            $('.hideIcon_right').removeClass('hide');
            showOrHide_right = true;
            $('.leaflet-right .leaflet-control').animate({'margin-right':'380px'},500)
        }
    });

    // 点击箭头 绘制窗口显示隐藏
    $('.hideBtn_left').click(function(){
        if(showOrHide_left){
            $('.left_panel').animate({left:'-340px'},500);
            $('.hideIcon_left').addClass('hide');
            showOrHide_left = false;
            $('.leaflet-left .leaflet-control').animate({'margin-left':'20px'},500);
            $('.myControl,#legendDiv').animate({left:'20px'},500);
        }else {
            $('.left_panel').animate({left:'20px'},500);
            $('.hideIcon_left').removeClass('hide');
            showOrHide_left = true;
            $('.leaflet-left .leaflet-control').animate({'margin-left':'380px'},500);
            $('.myControl,#legendDiv').animate({left:'380px'},500);
        }
    });

    // 树结构tab切换
    $('.treeTab').click(function(){
        $(this).addClass('active').siblings().removeClass('active');
        var index = $(this).index();
        $('.treelist').eq(index).show().siblings().hide();
    });

    // 详细信息tab切换
    $('.d_tabs li').click(function(){
        $(this).addClass('active').siblings().removeClass('active');
        var index = $(this).index();
        $('.d_tabContent .d_cont').eq(index).show().siblings('.d_cont').hide();
    });

    //点击搜索按钮
    $('#searchBtn').click(function(){
        var searchVal=$.trim($('#searchInput').val());
        var reg =/^\s*$/;  //完全匹配0个或多个空格
        if(! reg.test(searchVal)){
            $('.cardlist').show();
            $('.detailsBox').hide();
            var Region_ID = '';  // 所在地区
            var CHR_ID = '';
            var DWType_ID = '';
            infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,false);
        }else {
            //$.toast({
            //    text: '搜索内容不能为空！',
            //    icon: 'info',
            //    position: "mid-center",
            //    stack: false,
            //    allowToastClose: false,
            //    loader: false,
            //    bgColor: "#3bb9d4",
            //    textColor: "#fff",
            //    timeout: 3000,
            //});
        }
    });

    // 返回搜索列表
    $('.d_back').click(function(){
        $('.detailsBox').hide();
        $('.cardlist').fadeIn();
    });

    // 点击排序
    $('.sortBox').find('li').click(function(){
        $(this).addClass('active').siblings().removeClass('active');
    });

    // 排序
    $('#ID').click(function(){
        sortTable($(this),".assetId");
    });
    $('#NAME').click(function(){
        sortTable($(this),".l_title");
    });
    $('#ADDRESS').click(function(){
        sortTable($(this),".addressId");
    });

    ajaxRegion();
    ajaxChr();
    ajaxDWType();

    //查看详情
    $('.ctab_cont').on('click','.c_lists',function(){
        var id = $(this).attr("name");
        $(this).addClass('active').siblings().removeClass('active');
        detailsClick(id)
    });

    chr_select = $('#ZGDW_Name').html(chrsult).customSelect({
        width:300,
        lineHeight:28,
    });
    reg_select = $('#Region_Name').html(regionsult).customSelect({
        width:300,
        lineHeight:28,
    });
    DWType_select = $('#DWType_Name').html(DWTypesult).customSelect({
        width:300,
        lineHeight:28,
    });
    UsingStatus_select = $('#UsingStatus').customSelect({
        width:300,
        lineHeight:28,
    });

    $(".slideImg").slide({mainCell:".bd ul",autoPlay:true});

    // 删除
    $('.ctab_cont').on('click','.deleteBtn',function(){
        var id = $(this).attr("name");
        $.confirmWin({
            width:250,
            height:120,
            title:"删除",
            text:"<div class='removeWarnContent'>您确定要删除该地块吗？</div>",
            btnVal:"确定",
            submitFn:function(){
                $('.c_lists[name='+id +']').remove();
                deleteFa(id);
            }
        });
        return false;
    });

    // 删除
    $('.deleteBtn_2').click(function(){
        var id = $(this).attr("name");
        $.confirmWin({
            width:250,
            height:120,
            title:"删除",
            text:"<div class='removeWarnContent'>您确定要删除该地块吗？</div>",
            btnVal:"确定",
            submitFn:function(){
                $('.ctab_cont').find('.c_lists[name='+id +']').remove();
                deleteFa(id);
            }
        });

    });

    //新增房产
    $('.addNew').click(function(){
        polygonLayer_editor.clearLayers();
        editorPolygons = [];
        aa = 0;
        showLayers();
        addNewFa();
    });

    //保存房产信息editorBtn
    $('.confirmBtn').click(function(){
        if(newPolygonData.length ==0){
            $.toast({
                text: '请添加地块！',
                icon: 'info',
                position: "mid-center",
                stack: false,
                allowToastClose: false,
                loader: false,
                bgColor: "red",
                textColor: "#fff",
                timeout: 2000,
            });
            return
        }
        var id = $(this).attr('name');
        if($('.confirmBtn').data('add')){
            //GeometryJsonPointStr,GeometryJsonPolygonStr
            oldObjInfo ={};
        }else{
            if(oldObjInfo.GeoJsonPoint){
                delete oldObjInfo.GeoJsonPoint;
            }
            if(oldObjInfo.GeoJsonPolygon){
                delete oldObjInfo.GeoJsonPolygon;
            }
        }
        $('.d_tabContent').find('input').each(function(){
            var type = $(this).attr('name');
            oldObjInfo[type] = $(this).val();
        });

        if(newPolygonData.length ==0){
            oldObjInfo.GeometryJsonPolygonStr = '';
            oldObjInfo.GeometryJsonPointStr = '';
        }else{
            oldObjInfo.GeometryJsonPolygonStr = JSON.stringify(newPolygonData);
            var lng = 0,lat = 0;
            for(var i=0;i<newPolygonData[0].length;i++){
                lng += newPolygonData[0][i][0];
                lat += newPolygonData[0][i][1];
            }
            lng = lng/newPolygonData[0].length;
            lat = lat/newPolygonData[0].length;
            var lnglat = [lng,lat];
            oldObjInfo.GeometryJsonPointStr = JSON.stringify(lnglat);
            editorPolygons = {
                geometry:{
                    coordinates:newPolygonData,
                    type:"Polygon"
                },
                type:"Feature"
            }
        }

        oldObjInfo.ID = parseInt(id);
        oldObjInfo.ZGDW_ID = chr_select.getValue();
        oldObjInfo.SYDW_ID = chrsy_select.getValue();
        oldObjInfo.Region_ID = reg_select.getValue();
        oldObjInfo.UsingStatus = UsingStatus_select.getValue();
        var reg =/^\s*$/;
        if(! reg.test($('#loc').find('input').val())){
            updatePlace(oldObjInfo);
        }else{
            $.toast({
                text: '资产名称不能为空！',
                icon: 'info',
                position: "mid-center",
                stack: false,
                allowToastClose: false,
                loader: false,
                bgColor: "red",
                textColor: "#fff",
                timeout: 2000,
            });
        }
        //
    });
    //取消
    $('.clearNewFA').click(function(){
        $('.right_panel').animate({right:'-340px'},500);
        $('.hideIcon_right').addClass('hide');
        showOrHide_right = false;
    });

    // 鼠标移到站点名出现提示信息
    $('.showTips').each(function(){
        $(this).mousemove(function(e){
            $('.tdTips p').html($(this).attr('name'));
            $('.tdTips').show().css({
                left:(e.pageX-20)+'px',
                top: (e.pageY-$('.tdTips').height()-10 )+'px'
            });
        });
        $(this).mouseout(function(){
            $('.tdTips').hide();
        });
    });

    $('.submitFile').click(function(){
        var fileList = $(".updateInput")[0].files;
        var faImageId = $('.confirmBtn').attr('name');
        var formData = new FormData();
        formData.append('id',faImageId);
        formData.append('file',fileList[0]);
        if(fileList.length == 0){
            $.toast({
                text: '请选择文件！',
                icon: 'info',
                position: "mid-center",
                stack: false,
                allowToastClose: false,
                loader: false,
                bgColor: "red",
                textColor: "#fff",
                timeout: 2000,
            });
            return
        }
        var size = fileList[0].size / 1024;
        var url = config.baseUrl + "/fa/faImageUpload.do";
        if(size >=512){         //图片大小规则：1*1000 = 1M
            $(".updateInput").val('');
            $.toast({
                text: '图片过大,请选择小于512KB的图片！',
                icon: 'info',
                position: "mid-center",
                stack: false,
                allowToastClose: false,
                loader: false,
                bgColor: "red",
                textColor: "#fff",
                timeout: 2000,
            });
            return
        }else{
            $.ajax({
                url: url,
                contentType: false,
                processData: false,
                type: "post",
                data:formData,
                success: function (jsondata) {
                    if(jsondata.code === 1){
                        $.toast({
                            text: '上传成功！',
                            icon: 'info',
                            position: "mid-center",
                            stack: false,
                            allowToastClose: false,
                            loader: false,
                            bgColor: "#3bb9d4",
                            textColor: "#fff",
                            timeout: 2000,
                        });
                        getFaImage(faImageId)
                        $(".updateInput").val('')
                    }
                }
            });
        }
    });

    $('#slideImg').on('click','.deleteImg',function(){
        var iid = $(this).attr('iid')
        var id  = $(this).attr('faid')
        var url = config.baseUrl + "/fa/deleteFaImage.do";
        $.ajax({
            url: url,
            data:{
                iid:iid
            },
            type: "post",
            success: function (jsondata) {
                if(jsondata.code === 1){
                    $.toast({
                        text: '删除成功！',
                        icon: 'info',
                        position: "mid-center",
                        stack: false,
                        allowToastClose: false,
                        loader: false,
                        bgColor: "#3bb9d4",
                        textColor: "#fff",
                        timeout: 2000,
                    });
                    getFaImage(id)
                }
            }
        })
    })


    $('.uploading').click(function(){
        $('.uploadBox').show()
    })

    $('.uploadConfirm,.uploadCancel,.uploadClose').click(function(){
        $('.uploadBox').hide()
    })
});


function getFaImage(id){
    var url = config.baseUrl + "/fa/getFaImage.do";
    $.ajax({
        url: url,
        data:{
            id:id
        },
        type: "post",
        success: function (jsondata) {
            $('.Slide.One').find('img').attr('src',jsondata[0]);
            var fa = jsondata.data;
            var strnum = '';
            var strimg = '';
            if(fa.length > 0){
                for(var i=0;i<fa.length;i++){
                    strnum +='<li>'+(i+1)+'</li>';
                    strimg += '<li><a href="javascript:;" class="Slide One" ><span class="deleteImg" iid="'+ fa[i].iid +'" faid="'+ fa[i].id+'"></span><img src="'+ fa[i].baseString+'" /></a></li> '
                }
                var str = '<div class="hd"><ul>'+ strnum+'</ul> </div> ' +
                    '<div class="bd"> <ul> ' +strimg +'</ul> </div>';
                $('#slideImg').empty().html(str);
                $(".slideImg").slide({mainCell:".bd ul",autoPlay:true});
            }else{
                var str = '<a href="javascript:;" class="Slide One" ><img src="../images/no-1.png" /></a>'
                $('#slideImg').html(str)
            }

        }
    })
}

//对象的key不确定，取value值
function getObjFirst(obj){
    for(var i in obj){
        return obj[i];
    }
}


//显示到地图
function showLayers(mapZoom){
    if(GYZCJsonLayer != null){
        GYZCJsonLayer.clearLayers();
    }
    //if(mapZoom <= turnLevel){   //显示点
    //    GYZCJsonLayer = L.geoJSON(Points, {
    //        pointToLayer:function(GeoJsonPoints,lng){
    //            return L.marker(lng,{
    //                pmIgnore: true,
    //                icon:myIcon.greed
    //            })
    //        }
    //    })
    //}else{   //显示面
        GYZCJsonLayer = L.geoJSON(Polygons, {
            pmIgnore: true,
            style: function(feature) {
                switch (feature.properties.DWType_Name) {
                    case '行政单位': return {color: "#ff9999"};
                    case '国有企业':   return {color: "#d27406"};
                    case '财政补助事业单位':   return {color: "#04a3e6"};
                    case '参照公务员法管理事业单位':   return {color: "#38c0f8"};
                    case '经费自理事业单位':   return {color: "#75d4fc"};
                    case '其他':   return {color: "#b7e0af"};
                }
            },
        });
    //}
    GYZCJsonLayer.bindTooltip(function(layer){
            return "<div class='tips'><h3 style='white-space:nowrap;font-size: 12px;'>"+layer.feature.properties.FA_Name +"</h3></div>";
        })
        .addTo(myMap);
}

function showHighLightLayer(mapZoom,data){
    if(highLightLayer != null){
        highLightLayer.clearLayers();
    }
    if(mapZoom <= turnLevel){   //显示点
        highLightLayer = L.geoJSON(data.Points, {
            pointToLayer:function(GeoJsonPoints,lng){
                return L.marker(lng,{
                    icon:myIcon.red
                })
            }
        })
    }else{      //显示面
        highLightLayer = L.geoJSON(data.Polygons, {
            style: function(feature) {
                return {color: "#fff600"}
            },
        });
    }
    highLightLayer.bindTooltip(function(layer){
            return "<div class='tips'><h3 style='white-space:nowrap;font-size: 12px;'>"+layer.feature.properties.FA_Name +"</h3></div>";
        })
        .addTo(myMap);
}

//控制地图显示点/面
function zoomLayers(mapZoom,data){
    //if( mapZoom <= turnLevel){
    //    if(zoomType) {
    //        if(GYZCJsonLayer != null){
    //            GYZCJsonLayer.clearLayers();
    //        }
    //        if(highLightLayer != null){
    //            highLightLayer.clearLayers();
    //        }
    //        GYZCJsonLayer = L.geoJSON(Points, {
    //                pmIgnore: true,
    //                pointToLayer:function(GeoJsonPoints,lng){
    //                    return L.marker(lng,{
    //                        icon:myIcon.greed
    //                    })
    //                }
    //            })
    //            .bindTooltip(function(layer){
    //                return "<div class='tips'><h3 style='white-space:nowrap;font-size: 12px;'>"+layer.feature.properties.FA_Name +"</h3></div>";
    //            })
    //            .addTo(myMap);
    //        if(data){
    //            highLightLayer = L.geoJSON(data.Points, {
    //                pointToLayer:function(GeoJsonPoints,lng){
    //                    return L.marker(lng,{
    //                        icon:myIcon.red
    //                    })
    //                }
    //            }).addTo(myMap)
    //        }
    //        zoomType = false;
    //    }
    //}
    //else{
        if(!zoomType){
            if(GYZCJsonLayer != null){
                GYZCJsonLayer.clearLayers();
            }
            if(highLightLayer != null){
                highLightLayer.clearLayers();
            }
            GYZCJsonLayer = L.geoJSON(Polygons, {
                    pmIgnore: true,
                    style: function(feature) {
                        switch (feature.properties.DWType_Name) {
                            case '行政单位': return {color: "#ff9999"};
                            case '国有企业':   return {color: "#d27406"};
                            case '财政补助事业单位':   return {color: "#04a3e6"};
                            case '参照公务员法管理事业单位':   return {color: "#38c0f8"};
                            case '经费自理事业单位':   return {color: "#75d4fc"};
                            case '其他':   return {color: "#b7e0af"};
                        }
                    },
                })
                .bindTooltip(function(layer){
                    return "<div class='tips'><h3 style='white-space:nowrap;font-size: 12px;'>"+layer.feature.properties.FA_Name +"</h3></div>";
                })
                .addTo(myMap);
            if(data){
                highLightLayer = L.geoJSON(data.Polygons, {
                    pmIgnore: true,
                    style: function(feature) {
                        return {color: "#fff600"}
                    },
                }).addTo(myMap);
            }
            zoomType = true;
        }
    //}

}

//排序
var sortTable = function($this,selector){
    //console.log($(this));
    if($this.data("isAsc")== null) $this.data("isAsc",true);
    else $this.data("isAsc",!$this.data("isAsc"));

    var $treeList = $(".c_lists");

    $.each($treeList, function(index, node) {
        node.sortValue = $(node).find(selector).text();
    });
    var isAsc = $this.data("isAsc");
    $treeList.sort(function(a,b){
        if(isAsc) {
            if (a.sortValue < b.sortValue) return 1;
            else if(a.sortValue > b.sortValue) return -1;
            else return 0;
        }
        else{
            if (a.sortValue > b.sortValue) return 1;
            else if(a.sortValue < b.sortValue) return -1;
            else return 0;
        }
    });
    $treeList.each(function(index){
        $(this).appendTo($(".ctab_cont"));
        $(this).find(".list_num").text(index+1);
    });
};

var selected;
var nodeData = [];

//区域
var regionsult = '';
function ajaxRegion(){
    $.ajax({
        url:config.serviceUrl+ "/api/Region",
        type:"Post",
        data:{
            "DATA": {
                "ID": "000",
                "Token" : Token,
            }
        },
        async: false,
        success:function(jsonData){
            var dataRegion = [];
            var regionData = jsonData.Region;
            for(var i=0;i<regionData.length;i++){
                var obj = {};
                obj.id = regionData[i].Region_ID;
                obj.text = regionData[i].Region_Name;
                obj.type = '2';
                obj.children = '';
                dataRegion.push(obj);
            }
            if(regionsult == ''){
                for(var i=0;i<regionData.length;i++) {
                    regionsult += '<option value="' + regionData[i].Region_ID + '">' + regionData[i].Region_Name + '</option>';
                }
            }
            getTree(dataRegion)
        },
    })


}

//单位
var chrsult = '';
function ajaxChr(){
    $.ajax({
        url:config.serviceUrl+ "/api/Chr",
        type:"Post",
        data:{
            "DATA": {
                "Prefix": "071",
                "Token" : Token,
            }
        },
        async: false,
    }).done(function (jsonData) {
        var dataChr = [];
        var CHRData = jsonData.CHR;
        for(var i=0;i<CHRData.length;i++) {
            var obj = {};
            var dataSubChr = [];
            for (var j = 0; j < CHRData[i].subCHR.length; j++) {
                var subObj = {};
                subObj.id = CHRData[i].subCHR[j].CHR_ID;
                subObj.text = CHRData[i].subCHR[j].CHR_Name;
                subObj.type = '2';
                subObj.children = '';
                dataSubChr.push(subObj);
            }
            obj.id = CHRData[i].CHR_ID;
            obj.text = CHRData[i].CHR_Name;
            obj.children = dataSubChr;
            obj.type = '1';
            obj.state = "closed";
            dataChr.push(obj);
        }
        if(chrsult==''){
            for(var i=0;i<CHRData.length;i++) {
                chrsult += '<option value="' + CHRData[i].CHR_ID + '">' + CHRData[i].CHR_Name + '</option>';
            }
        }
        getTree2(dataChr)
    })
}

// 根据主管单位得到使用单位
function getChr_sySelect (chrVal,setValue){
    $.post(config.serviceUrl+ "/api/Chr", {
            "DATA": {
                "Prefix": chrVal,
                "Token" : Token,
                "async":true
            }
        },
        function (jsonData) {
            if(jsonData !=null){
                if(jsonData.CHR[0].subCHR){
                    var chrsy = jsonData.CHR[0].subCHR;
                    var chrsysult = '';
                    for(var i=0; i<chrsy.length;i++){
                        chrsysult +='<option value="'+ chrsy[i].CHR_ID+'">'+ chrsy[i].CHR_Name +'</option>';
                    }
                    $('#SYDW_Name').prev('.select_box').remove();
                    chrsy_select = $('#SYDW_Name').html(chrsysult).customSelect({
                        width:300,
                        lineHeight:28,
                    });
                    chrsy_select.setValue(setValue)
                }
            }
        }
    );
}

//单位性质
var DWTypesult = '';
function ajaxDWType(){
    $.ajax({
        url:config.serviceUrl+ "/api/DWType",
        type:"Post",
        data:{
            "DATA": {
                "ID": "000",
                "Token" : Token,
            }
        },
        async: false,
    }).done(function (jsonData) {
        var dataDWType = [];
        for(var i=0 ;i<jsonData.DWType.length;i++){
            var obj = {};
            obj.id = jsonData.DWType[i].DWType_ID;
            obj.text = jsonData.DWType[i].DWType_Name;
            obj.type = '2';
            obj.children = '';
            dataDWType.push(obj);
        }
        if(DWTypesult==''){
            for(var i=0;i<jsonData.DWType.length;i++) {
                DWTypesult += '<option value="' + jsonData.DWType[i].DWType_ID + '">' + jsonData.DWType[i].DWType_Name + '</option>';
            }
        }
        getTree3(dataDWType);
    })
}

// 得到区域树列表
function getTree(dataRegion){
    $("#listTree").tree({
        lines:true,
        animate:true,
        data: [{
            id:'000',
            text: '所在地区',
            state: 'open',
            type:'1',
            children: dataRegion,
        }],
        onLoadSuccess:function(){
        },
        onClick:function(node){
        },
        onSelect:function(node){
            var searchVal = '';
            var DWType_ID = '';
            var Region_ID = node.id;
            var CHR_ID = '';


            if(editFlag == true){
                $.confirmWin({
                    width:250,
                    height:120,
                    title:"删除",
                    text:"<div class='removeWarnContent'>是否保存当前修改地块？</div>",
                    btnVal:"确定",
                    submitFn:function(){
                        $('.confirmBtn').trigger('click')
                    },
                    cancelFn:function(){
                        if(node.type == '2'){  // 得到树的子列表
                            selected = $('#listTree').tree('getSelected');
                            infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,true)
                        }else if(node.type == '3'){                     // 请求详情
                            detailsClick(node.id);
                        }
                    }
                });
            }else{
                if(node.type == '2'){  // 得到树的子列表
                    selected = $('#listTree').tree('getSelected');
                    infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,true)
                }else if(node.type == '3'){                     // 请求详情
                    detailsClick(node.id);
                }
            }

        },
    });

}

// 得到单位树列表
function getTree2(dataChr){
    $("#listTree2").tree({
        lines:true,
        animate:true,
        data: [{
            id:'071',
            text: '主管单位',
            state:'open',
            type:'1',
            children:dataChr,
        }],
        onLoadSuccess:function(){
        },
        onClick:function(node){
        },
        onSelect:function(node){
            var DWType_ID = '';
            var searchVal = '';
            var Region_ID =""  ;
            var CHR_ID = node.id ;

            if(editFlag == true){
                $.confirmWin({
                    width:250,
                    height:120,
                    title:"删除",
                    text:"<div class='removeWarnContent'>是否保存当前修改地块？</div>",
                    btnVal:"确定",
                    submitFn:function(){
                        $('.confirmBtn').trigger('click')
                    },
                    cancelFn:function(){
                        if(node.type == '2'){  // 得到树的子列表
                            selected = $('#listTree2').tree('getSelected');
                            infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,true)
                        }else if(node.type == '3'){                     // 请求详情
                            detailsClick(node.id);
                        }
                    }
                });
            }else{
                if(node.type == '2'){  // 得到树的子列表
                    selected = $('#listTree2').tree('getSelected');
                    infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,true)
                }else if(node.type == '3'){                     // 请求详情
                    detailsClick(node.id);
                }
            }
        },
    });
}

// 得到单位性质树列表
function getTree3(dataDWType){
    $("#listTree3").tree({
        lines:true,
        animate:true,
        data: [{
            id:'071',
            text: '单位性质',
            state:'open',
            type:'1',
            children:dataDWType,
        }],
        onLoadSuccess:function(){
        },
        onClick:function(){
        },
        onSelect:function(node){
            var Region_ID =""  ;
            var CHR_ID = '' ;
            var DWType_ID = node.id ;
            var searchVal = '';

            if(editFlag == true){
                $.confirmWin({
                    width:250,
                    height:120,
                    title:"删除",
                    text:"<div class='removeWarnContent'>是否保存当前修改地块？</div>",
                    btnVal:"确定",
                    submitFn:function(){
                        $('.confirmBtn').trigger('click')
                    },
                    cancelFn:function(){
                        if(node.type == '2'){  // 得到树的子列表
                            selected = $('#listTree3').tree('getSelected');
                            infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,true)
                        }else if(node.type == '3'){                     // 请求详情
                            detailsClick(node.id);
                        }
                    }
                });
            }else{
                if(node.type == '2'){  // 得到树的子列表
                    selected = $('#listTree3').tree('getSelected');
                    infoTreeNode(searchVal,Region_ID,CHR_ID,DWType_ID,true)
                }else if(node.type == '3'){                     // 请求详情
                    detailsClick(node.id);
                }
            }
        },
    });
}

// 得到树的子节点
/*
 * flag: {
 *   true:插入树的子内容 + 搜索
 *   false：只有搜索
 *  }
 * */
function infoTreeNode(searchVal,RegionInfoID,CHRInfoID,DWType_ID,flag){
    editFlag = false;
    var url = config.serviceUrl+ "/api/Fa";
    $.post(url, {
            "DATA": {
                "Action": 'Search',
                "Wildcards": searchVal,
                "Region_ID": RegionInfoID,     //可省略
                "CHR_ID": CHRInfoID,      //可省略
                "DWType_ID":DWType_ID, //单位性质
                "Token":Token,
            }
        },
        function (data) {
            //GYZCJsonLayer_point.clearLayers();
            polygonLayer_editor.clearLayers();
            if(data.Success == true){
                if(GYZCJsonLayer != null){
                    GYZCJsonLayer.clearLayers();
                }
                $('.right_panel').show().animate({right:'20px'},500);
                $('.drawCon').animate({right:'380px'},500);
                showOrHide_right = true;
                $('.leaflet-right .leaflet-control').animate({'margin-right':'380px'},500)
                $('.cardlist').show();
                $('.detailsBox').hide();
                Polygons = [];
                Points = [];
                var fa = data.FA;
                var result='';
                stationInfo = {};
                nodeData = [];
                if(data.FA != undefined){
                    var lgtdArrays = [];
                    var lttdArrays = [];
                    if(data.FA != null && data.FA.length>0){
                        for(var i=0;i<fa.length;i++){
                            var nodeObj ={};
                            nodeObj.id = fa[i].ID;
                            nodeObj.code = fa[i].CODE;
                            nodeObj.text = fa[i].FA_Name;
                            nodeObj.type = '3',
                                nodeData.push(nodeObj);

                            var obj = fa[i];
                            var y = 28.9,x = 120.03;
                            if(fa[i].GeoJsonPoint){
                                var coordinates = fa[i].GeoJsonPoint.geometry.coordinates;
                                y=coordinates[1];
                                x=coordinates[0];
                                Points.push(fa[i].GeoJsonPoint);
                            }
                            if(fa[i].GeoJsonPolygon){
                                Polygons.push(fa[i].GeoJsonPolygon);
                            }
                            lgtdArrays.push(y);
                            lttdArrays.push(x);

                            result += '<div class="c_lists" name="'+obj.ID+'">' +
                                '<a class="deleteBtn" name="'+obj.ID+'"></a> ' +
                                '<div class="clearfix"><b class="list_num fl">'+(i+1)+'</b><h3 class="l_title fl list_tit">'+filValue(obj.FA_Name)+'</h3></div> ' +
                                '<ui> ' +
                                '<li><p>资产编号:&nbsp;</p><b class="assetId">'+filValue(obj.CODE)+'</b></li> ' +
                                '<li><p>房屋用途:&nbsp;</p><b>'+filValue(obj.Purpose)+'</b></li> ' +
                                '<li><p>使用单位:&nbsp;</p><b>'+filValue(obj.SYDW_Name)+'</b></li> ' +
                                '<li><p>坐落位置:&nbsp;</p><b class="addressId">'+filValue(obj.Address)+'</b></li> ' +
                                '</ui> ' +
                                '</div>';

                            stationInfo[obj.ID] = {
                                ID:obj.ID,
                                CODE:obj.CODE,
                                name:obj.FA_Name,
                                Address:obj.Address,
                                Purpose:obj.Purpose,
                                SYDW_Name:obj.SYDW_Name,
                                lgtd:x,
                                lttd:y,
                            };
                            //getHighLightStation(stationData,name)
                        }
                    }
                    showLayers(myMap.getZoom());
                    lgtdArrays.sort();
                    lttdArrays.sort();
                    var minLoctions = [lgtdArrays[0],lttdArrays[0]];
                    var maxLoctions = [lgtdArrays[lgtdArrays.length-1],lttdArrays[lgtdArrays.length-1]];
                    MapCenter(minLoctions,maxLoctions);
                }else{
                    result ='<p style="line-height: 30px;text-align: center">当前查询无匹配信息</p>';
                }


                // flag == true: 插入树的子项
                if(flag){
                    if(RegionInfoID != ''){
                        var node = $('#listTree').tree('getChildren',selected.target);
                        for(var i=0 ;i<node.length;i++){
                            $('#listTree').tree('remove',node[i].target);
                        }
                        $('#listTree').tree('append', {
                            parent: selected.target,
                            data: nodeData
                        });
                    }
                    else if(CHRInfoID != ''){
                        var node = $('#listTree2').tree('getChildren',selected.target);
                        for(var i=0 ;i<node.length;i++){
                            $('#listTree2').tree('remove',node[i].target);
                        }
                        $('#listTree2').tree('append', {
                            parent: selected.target,
                            data: nodeData
                        });
                    }
                    else{
                        var node = $('#listTree3').tree('getChildren',selected.target);
                        for(var i=0 ;i<node.length;i++){
                            $('#listTree3').tree('remove',node[i].target);
                        }
                        $('#listTree3').tree('append', {
                            parent: selected.target,
                            data: nodeData
                        });
                    }
                }
                $('.ctab_cont').html(result);
            }
        }
    )
}

// 地块详情
var faInfo = function(data){
    getFaImage(data.FA[0].ID);
    $('.updateInput').val('');
    aa = 0 ;
    $('.drawEnd').trigger('click');
    $('.drawCon').animate({right:'380px'},500);
    $('.right_panel').show().animate({right:'20px'},500);
    $('.hideIcon_right').removeClass('hide');
    showOrHide_right = true;
    $('.confirmBtn').data('add',false);
    $('.cardlist').hide();
    $('.detailsBox').fadeIn();
    $('.d_back,.deleteBtn_2').show();
    $('.clearNewFA,.newFaTitle').hide();
    var fa = data.FA;
    oldObjInfo = fa[0];
    if(fa[0].GeoJsonPolygon != undefined){
        if(fa[0].GeoJsonPoint != undefined){
            oldObjInfo.GeometryJsonPointStr=JSON.stringify(fa[0].GeoJsonPoint.geometry.coordinates);
        }
        oldObjInfo.GeometryJsonPolygonStr=JSON.stringify(fa[0].GeoJsonPolygon.geometry.coordinates);
        editorPolygons = fa[0].GeoJsonPolygon;
        newPolygonData = fa[0].GeoJsonPolygon.geometry.coordinates;
        polygonLayer_editor.clearLayers();
        polygonLayer_editor.addData(editorPolygons);
        aa++
    }else{
        newPolygonData = [];
    }
    var view3dUrl = '';
    var stationData = {};
    highLightData = {};
    editor_id = fa[0].ID;
    var coordinates = [28.9, 120.03];
    if(fa[0].GeoJsonPoint){
        coordinates = fa[0].GeoJsonPoint.geometry.coordinates;
        coordinates = [coordinates[1],coordinates[0]];
        stationData.Points = fa[0].GeoJsonPoint;
        highLightData.Points = fa[0].GeoJsonPoint;
    }
    if(fa[0].GeoJsonPolygon){
        stationData.Polygons = fa[0].GeoJsonPolygon;
        highLightData.Polygons = fa[0].GeoJsonPolygon;
    }
    $('.confirmBtn').attr('name',fa[0].ID);
    $('.deleteBtn_2').attr('name',fa[0].ID);

    $('.d_tabContent').find('input').each(function(){
        $(this).val(filValue(fa[0][$(this).attr('name')]))
    });
    setview(coordinates);
    view3dUrl = fa[0].View3d;
    if(view3dUrl == null || view3dUrl == undefined){view3dUrl = 'http://map.baidu.com/';}

    $('.location').click(function(){
        setview(coordinates)
    });
    showHighLightLayer(myMap.getZoom(),stationData);
    chr_select.setValue(fa[0].ZGDW_ID);
    getChr_sySelect (fa[0].ZGDW_ID,fa[0].SYDW_ID);
    chr_select.change(function(){
        var chrVal = chr_select.getValue();
        getChr_sySelect(chrVal);
    });
    reg_select.setValue(fa[0].Region_ID);
    UsingStatus_select.setValue(fa[0].UsingStatus);
    //查看3D视图
    $('.btn_3D').click(function(){
        $('#view3D').find('iframe').attr('src',view3dUrl);
        $('#view3D').show();
    });
    $('#close3D').click(function(){
        $('#view3D').hide();
    });

};

// 点击详情请求数据
var detailsClick = function(id){
    editFlag = false;
    aa = 0;
    polygonLayer_editor.clearLayers();
    //highLightLayer.clearLayers();
    var url = config.serviceUrl+ "/api/Fa";
    $.post(url, {
            "DATA": {
                "Action": "SearchByID",  //SearchByID,SearchByXY,Search
                "ID": id, //配合SearchByID 使用
                "Token":Token,
            }
        },
        function (data) {
            if(data.Success == true){
                faInfo(data)
            }
            else {
                $.toast({
                    text: '数据出错！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "red",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }

        });
};

// 地图定位
var setview = function(data){
    myMap.setView([data[0],data[1]],locationLevel);
};

var filValue = function(x){
    if(x==="" || typeof(x) == "undefined" || x==null || x == "undefined"){
        return "";
    }else {
        return x;
    }
};

// 更新地块
function updatePlace(data){
    var url = config.serviceUrl+ "/api/Fa";
    $.post(url, {
            "DATA": {
                "Action": "updateOrInsertFa",
                "FA":data,
                "Token":Token,
            }
        },
        function (jsondata) {
            if(jsondata.Success == true){
                ajaxRegion();
                ajaxChr();
                ajaxDWType();
                $.toast({
                    text: '保存成功！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "#3bb9d4",
                    textColor: "#fff",
                    timeout: 2000,
                });
                $('.drawEnd').trigger('click')
                detailsClick(data.ID);
                editFlag = false;
                var aaurl = config.serviceUrl+ "/api/Fa";
                if(myMap.getZoom() <= turnLevel){
                    zoomType= false;
                }else{
                    zoomType= true;
                }
                $.post(aaurl, {
                        "DATA": {
                            "Action": "getGeometry",  //SearchByID,SearchByXY,Search
                            "Token":Token,
                        }
                    },
                    function (data) {
                        if(data.GeoJsonPolygons.length>0){
                            for(var i=0;i<data.GeoJsonPolygons.length;i++){
                                if(data.GeoJsonPolygons[i] != null){
                                    Polygons.push(data.GeoJsonPolygons[i])
                                }
                            }
                            for(var i=0;i<data.GeoJsonPoints.length;i++){
                                if(data.GeoJsonPoints[i] != null){
                                    Points.push(data.GeoJsonPoints[i])
                                }
                            }
                        }
                        showLayers(myMap.getZoom())
                    }
                );
            }else {
                $.toast({
                    text: '保存失败！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "red",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }

        })
}

// 删除地块
var deleteFa = function(id) {
    $('.detailsBox').hide();
    $('.cardlist').fadeIn();
    var url = config.serviceUrl + "/api/Fa";
    $.post(url, {
            "DATA": {
                "Action": "DeleteFA",
                "FA": { "ID": id },
                "Token": Token,
            }
        },
        function (result) {
            if(result.Success == true){
                var $treeList = $(".c_lists");
                $treeList.each(function(index){
                    $(this).appendTo($(".ctab_cont"));
                    $(this).find(".list_num").text(index+1);
                });
                ajaxRegion();
                ajaxChr();
                ajaxDWType();
                $.toast({
                    text: '删除成功！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "#3bb9d4",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }
        });
};

// 添加地块
var addNewFa = function(){
    var url = config.serviceUrl + "/api/Fa";
    $.post(url, {
            "DATA": {
                "Action": "NewFA",
                "Token": Token,
            }
        },
        function (data) {
            if(data.Success == true){
                $('.right_panel').show().animate({right:'20px'},500);
                $('.drawCon').animate({right:'380px'},500);
                $('.leaflet-right .leaflet-control').animate({'margin-right':'380px'},500);
                showOrHide_right = true;
                $('.detailsBox').fadeIn();
                $('.cardlist,.d_back,.deleteBtn_2').hide();
                $('.clearNewFA,.newFaTitle').show();
                $('.confirmBtn').attr('name',data.FA[0].ID);
                $('.d_tabContent').find('input').each(function(){
                    $(this).val('')
                });
                getChr_sySelect ('071001','071001001');
                $('.confirmBtn').data('add',true);
                editor_id = data.FA[0].ID;
            }
        });
};

// 根据经纬度获取地块
var test_SearchByXY = function(LevelXY) {
    if(ifGetFa == true){
        var url = config.serviceUrl + "/api/Fa";
        if(editFlag == true){
            $.confirmWin({
                width: 250,
                height: 120,
                title: "删除",
                text: "<div class='removeWarnContent'>是否保存当前修改地块？</div>",
                btnVal: "确定",
                submitFn: function () {
                    $('.confirmBtn').trigger('click')
                },
                cancelFn: function () {
                    $.post(url, {
                            "DATA": {
                                "Action": "SearchByXY",     //SearchByID,SearchByXY,Search
                                "LevelXY": LevelXY,  //配合SearchByXY 使用
                                "Token": Token
                            }
                        },
                        function (data) {
                            if(data.Success == true){
                                if(data.FA && data.FA.length>0){
                                    $('.right_panel').show().animate({right:'20px'},500);
                                    showOrHide_right = true;
                                    faInfo(data)
                                }
                            }
                        });
                }
            })
        }else{
            $.post(url, {
                    "DATA": {
                        "Action": "SearchByXY",     //SearchByID,SearchByXY,Search
                        "LevelXY": LevelXY,  //配合SearchByXY 使用
                        "Token": Token
                    }
                },
                function (data) {
                    if(data.Success == true){
                        if(data.FA && data.FA.length>0){
                            $('.right_panel').show().animate({right:'20px'},500);
                            showOrHide_right = true;
                            faInfo(data)
                        }
                    }
                });
        }

    }

}

